import requests
import base64
import os

def get_card_number(api_url, api_key, image_path):
    """
    通过 API 识别图片中的卡号。如果出现错误，将返回 None 和错误信息。

    参数:
    - api_url (str): API 的 URL 地址
    - api_key (str): API 的授权密钥
    - image_path (str): 图片的本地路径

    返回:
    - str: 识别到的卡号，如果失败返回 None 和错误信息
    """
    # 请求头
    headers = {
        "Content-Type": "application/json",
        "Authorization": f"Bearer {api_key}"
    }

    # 检查图片文件是否存在
    if not os.path.exists(image_path):
        return None, "图片路径不存在"

    # 读取图片并转为 Base64 编码
    with open(image_path, "rb") as image_file:
        base64_image = base64.b64encode(image_file.read()).decode("utf-8")

    # 构造请求数据
    data = {
        "seed": None,
        "stop": None,
        "temperature": 0.1,
        "top_p": 1,
        "max_tokens": 1024,
        "model": "qwen2-vl",
        "messages": [
            {
                "role": "user",
                "content": [
                    {
                        "type": "image_url",
                        "image_url": {
                            "url": f"data:image/jpeg;base64,{base64_image}"
                        }
                    }
                ]
            },
            {
                "role": "user",
                "content": "识别图里的数字"
            }
        ]
    }

    # 发送 POST 请求
    response = requests.post(api_url, headers=headers, json=data)

    # 检查请求是否成功
    if response.status_code == 200:
        # 请求成功，解析响应内容
        response_data = response.json()
        content=response_data['choices'][0]['message']['content']

        return content,None

    else:
        # 请求失败，返回错误信息
        return None, f"请求失败，状态码：{response.status_code}, 错误信息：{response.text}"

# 示例调用
if __name__ == "__main__":
    print('start')
    API_KEY = "gpustack_2d61aef57d5d2e2a_80df8663370f15869075d999effdc4ff"
    API_URL = "http://10.104.8.16/v1-openai/chat/completions"
    image_path = "R-C.jpg"

    result, error = get_card_number(API_URL, API_KEY, image_path)

    if error:
        print(f"识别失败，错误信息：{error}")
    else:
        print(f"识别成功，卡号是：{result}")
